#include "stdafx.h"
#include <JeayeSDK/JArray.h>
#include <JeayeSDK/c_memory.h>

#ifdef _DEBUG
#define new new(__FILE__, __LINE__)
#endif

static BOOL  static_array_expand(JArray *thiz, UINT slot_size)
{
	INT32 data_count = thiz->count;
	PVOID* data = thiz->data;
	thiz->data = new PVOID[slot_size];
	if (thiz->data == NULL) {
		thiz->data = data;
		return FALSE;
	}
	memcpy(thiz->data, data, data_count * sizeof(PVOID));

	thiz->size = slot_size;
	thiz->count = data_count;

	delete[] data;
	return TRUE;
}

JArray::JArray(UINT initsize)
{
	create(initsize);
}
JArray::~JArray()
{
	destroy();
}
BOOL JArray::create(UINT initsize)
{
	this->size = initsize;
	this->count = 0;
	this->data = new PVOID[initsize];
	if(this->data == NULL){
		C_ERROR_LOG(_T("create cc_array_t : No more memory for allocating data"));
		return FALSE;
	}
	return TRUE;
}

void* JArray::find(const UINT index)
{
	if (this->size <= index) {
		return NULL;
	}

	return this->data[index];
}

void JArray::append(const JArray* append)
{
	UINT32 size = 0;
	_ASSERT(this != NULL && append != NULL);
	if (this == NULL || append == NULL)
		return ;

	size = this->count + append->count;
	/*if not enough space,expand first*/
	if (this->size <= 0x80000000 && size > this->size) {
		static_array_expand(this, size);
	}

	memcpy(this->data[this->count], append->data[0], append->count * sizeof(PVOID));

	this->count = size;
}

void JArray::insert(const UINT index,void* data)
{
	_ASSERT(this != NULL && data != NULL);
	if (this == NULL || data == NULL)
		return;

	/*if not enough space,expand first*/
	if (this->size <= 0x80000000 && index >= this->size) {
		static_array_expand(this, index + 2);
	}

	if (index >= this->size) {
		return ;
	}

	if (index >= this->count) {
		this->count++;
	}

	this->data[index] = data;
}

void* JArray::pop()
{
	return remove(this->count - 1);
}

void* JArray::remove(const UINT index)
{
	UINT i = 0;
	UINT count = 0;
	void* data = NULL;

	_ASSERT(this->size > index);
	if (this->size <= index)
		return NULL;

	data = this->data[index];
	count = this->count - 1;

	for (i = index; i < count; i++) {
		this->data[i] = this->data[i + 1];
	}

	this->count = count;

	return data;
}

void JArray::cleanup()
{
	memset(this->data, 0, sizeof(PVOID) * this->count);
	this->count = 0;
}

void JArray::destroy()
{
	delete[] this->data;
}
